<template>
  <div class="editPage__video">
    <div class="img__con">
      <el-upload ref="upload" class="avatar-uploader" :action="uploadImgUrl" :data="uploadImgData" :accept="accept"
        :headers="uploadHeaders" :show-file-list="false" :before-upload="beforeAvatarUpload" :disabled="disabled"
        :http-request="uploadFile" :auto-upload="false" :on-change="uploadHandler" :limit="1">
        <el-button v-if="!imageUrl" size="small" icon="el-icon-upload" :disabled="disabled">{{ buttonText }}</el-button>
        <div slot="tip" class="el-upload__tip" v-show="showTip" v-if="!imageUrl">
          <span>
            {{ `只能上传一个不超过${fileSize}${sizeUnit}的${accept}文件` }}
          </span>
        </div>
      </el-upload>

      <!-- <video width="100%" v-if="imageUrl" controls="controls" :key="menuKey">
        <source :src="imageUrl" type="video/mp4" />
      </video> -->
      <JADP-Video v-if="imageUrl" :url="imageUrl" ref="JADPVideo"></JADP-Video>
    </div>
  </div>
</template>
<script>
import request from "@/utils/request";
import { ossUpload } from "@/utils/oss";
const units = {
  KB: 1024,
  MB: 1024 * 1024,
  GB: 1024 * 1024 * 1024
};
export default {
  name: "UploadVideo",
  props: {
    value: {
      default: null
    },
    disabled: {
      type: Boolean,
      default: false
    },
    showTip: {
      type: Boolean,
      default: false
    },
    accept: {
      type: String,
      default: "*"
    },
    buttonText: {
      type: String,
      default: "选择视频"
    },
    sizeUnit: {
      type: String,
      default: "MB"
    },
    fileSize: {
      default: 2
    },
    audio: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      imageUrl: null,
      // 视频上传
      uploadImgUrl: `${this.define.comUploadUrl}/upload`,
      uploadHeaders: { Authorization: this.$store.getters.token },
      uploadImgData: { busiName: 32 },
      // 应付多个组件的情况 记录当前组件的key值
      componentKey: null,
      menuKey: 1, // 用来强制刷新
      //   videoFlag: false, // 进度条相关的
      //   videoUploadPercent: 0, // 进度条相关的
      loading: false,
      formData: "",
      intervalId: null
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        if (typeof val === "string") {
          this.imageUrl = JSON.parse(val).ossAddress;
        }
      }
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const unitNum = units[this.sizeUnit];
      if (!this.fileSize) return true;
      let isRightSize = file.size / unitNum < this.fileSize;
      if (!isRightSize) {
        this.$message.error(`文件大小不能超过${this.fileSize}${this.sizeUnit}`);
      }
      return isRightSize;
    },
    // 上传文件
    uploadFile(file) {
      this.formData.append("file", file.file); // append增加数据
      //   this.formData.append("file", file.file); // append增加数据
    },
    uploadHandler(file) {
      console.log(
        document.getElementsByClassName("el-upload__input")[0].value,
        "本地电脑路径"
      );
      this.formData = null;
      this.formData = new FormData();
      console.log(file, "上传文件", this.formData)
      this.$refs.upload.submit(); // 提交调用uploadFile函数
      this.loading = this.$loading({
        lock: true,
        text: `正在上传文件...`,
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });

      ossUpload(file, this.callBack).then(res => {
        this.imageUrl = res.ossAddress;
        this.$emit("input", JSON.stringify(res));
        // 获取视频时长
        var audioElement = new Audio(this.imageUrl);
        var duration;
        audioElement.addEventListener("loadedmetadata", () => {
          duration = parseInt(audioElement.duration); //时长为秒
          this.$emit("duration", duration);
        });
      }).catch(err => {
        this.$message.error("上传错误,请刷新重试");
      }).finally(() => {
        this.loading.close();
      });

      // request({
      //   url: this.uploadImgUrl,
      //   method: "post",
      //   data: this.formData,
      //   headers: this.uploadHeaders,
      //   onUploadProgress: e => {
      //     console.log(e, 3);
      //     if (e.lengthComputable) {
      //       var uploadRate = (e.loaded / e.total) * 100;
      //       if (uploadRate >= 100) {
      //         this.loading.setText("已上传成功，正在加载资源，请稍后······");
      //       } else {
      //         this.loading.setText(`正在上传文件 ${uploadRate.toFixed(1)}%`);
      //       }
      //     }
      //   }
      // })
      // .then(res => {
      //   console.log(res, 111);
      //   // ++this.menuKey;
      //   this.imageUrl = res.data[0].ossAddress;
      //   this.$emit("input", JSON.stringify(res.data[0]));
      //   // 获取视频时长
      //   var audioElement = new Audio(this.imageUrl);
      //   var duration;
      //   audioElement.addEventListener("loadedmetadata", () => {
      //     duration = parseInt(audioElement.duration); //时长为秒
      //     this.$emit("duration", duration);
      //   });
      // })
      // .catch(err => {
      //   this.$message.error("上传错误,请刷新重试");
      // })
      // .finally(() => {
      //   this.loading.close();
      //   // clearInterval(this.intervalId);
      //   // request({
      //   //   url: "/api/xy/file/resetPercent"
      //   // }).then(res => {
      //   //   console.log(res, 222222);
      //   // });
      // });

      // this.intervalId = setInterval(() => {
      //   request({
      //     url: "/api/xy/file/percent"
      //   }).then(res => {
      //     console.log(res, 222222);
      //   });
      // }, 500);
    },
    callBack(p) {
      var uploadRate = Math.floor(p * 100);
      if (uploadRate >= 100) {
        this.loading.setText("已上传成功，正在加载资源，请稍后······");
      } else {
        this.loading.setText(`正在上传文件 ${uploadRate.toFixed(1)}%`);
      }
    }
    // beforeDestroy() {
    //   clearInterval(this.intervalId);
    //   request({
    //     url: "/api/xy/file/percent"
    //   }).then(res => {
    //     console.log(res, 222222);
    //   });
    // }
  }
};
</script>

<style lang="scss" scoped></style>
